<template>
  <div class="controls">
    <input
      autocomplete="off"
      class="itxt"
      :value="currentNum"
      @blur="handlerBlur"
    />
    <a
      href="javascript:"
      @click="currentNum++"
      :class="{ plus: true, disable: currentNum === max }"
      >+</a
    >
    <a
      href="javascript:"
      @click="currentNum--"
      :class="{ mins: true, disable: currentNum === min }"
      >-</a
    >
  </div>
</template>

<script>
export default {
  name: "InputNumber",
  props: {
    value: Number,
    min: {
      type: Number,
      default: 1,
    },
    max: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      currentNum: this.value,
    };
  },
  watch: {
    currentNum(newNum, oldNum) {
      // 转数字
      let number = +newNum;
      const { min, max } = this;
      // 如果不是纯数字则设置会原来的值
      if (isNaN(number)) number = oldNum;
      // 如果小于最小值 则设置为最小值
      if (number < min) number = min;
      // 如果大于最大值 则设置为最大值
      if (number > max) number = max;

      // 统一设置
      this.currentNum = number;
      // 设置外面的值
      this.$emit("input", number);
    },
  },
  methods: {
    // 更新值
    handlerBlur(e) {
      this.currentNum = e.target.value;
    },
  },
};
</script>

<style scoped>
.controls {
  width: 48px;
  position: relative;
  float: left;
  margin-right: 15px;
}
.itxt {
  width: 38px;
  height: 37px;
  border: 1px solid #ddd;
  color: #555;
  float: left;
  border-right: 0;
  text-align: center;
}
.disable {
  color: #ccc !important;
  background-color: aquamarine;
}
.plus,
.mins {
  width: 15px;
  text-align: center;
  height: 17px;
  line-height: 17px;
  background: #f1f1f1;
  color: #666;
  position: absolute;
  right: -8px;
  border: 1px solid #ccc;
}

.mins {
  right: -8px;
  top: 19px;
  border-top: 0;
}

.plus {
  right: -8px;
}
</style>
